<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="标题" prop="title">
            <el-input v-model="formItem.title" placeholder="请输入标题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类型" prop="categories">
            <el-radio-group v-model="formItem.categories" size="mini" @change="categorieChange">
              <el-radio label="1" value="1" border>固定资产</el-radio>
              <!-- <el-radio label="2" value="2" border>低值易耗品</el-radio> -->
              <el-radio label="3" value="3" border>消耗品</el-radio>
              <el-radio label="4" value="4" border>配件</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="用途" prop="reason">
            <el-input v-model="formItem.reason" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="综合管理部" prop="comprehensive">
            <el-radio-group v-model="formItem.comprehensive">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formItem.remark" type="textarea" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="需求明细">
            <el-button size="mini" type="primary" icon="el-icon-plus" style="margin-bottom: 15px;" @click="addRequire">新增需求</el-button>
            <PageableTable
              :loading="false"
              :table-height="240"
              :data="formItem.recipientRequires"
              :disable-pageable="true"
              border
              class="fixed-table-table"
            >
              <el-table-column
                label="序号"
                type="index"
                width="50"
                header-align="center"
                align="center"
              />
              <el-table-column v-for="column in insideColumns" :key="column.key" header-align="center" align="center" :label="column.title" :prop="column.key" :sortable="column.sortable">
                <template slot-scope="scope">
                  <column-render :render="column.render" :row="scope.row" :column="column" />
                </template>
              </el-table-column>
              <el-table-column label="领用数量" header-align="center" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.quantity }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" header-align="center" align="center" width="150" class-name="small-padding fixed-width" fixed="right">
                <template slot-scope="{row}">
                  <el-button type="text" size="mini" icon="el-icon-edit" title="编辑" @click="edit(row)">编辑</el-button>
                  <el-button type="text" size="mini" icon="el-icon-delete" title="删除" @click="remove(row)">移除</el-button>
                </template>
              </el-table-column>
            </PageableTable>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="">
            <el-button size="mini" @click="btnCancel">取 消</el-button>
            <el-button type="primary" @click="commit">提交</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <FormDialog v-if="requireDialogFormVisible" width="40%" title="新增需求" :append-to-body="true" :show="requireDialogFormVisible" @on-ok="selectOk" @on-cancel="selectCancel">
      <RequireEdit v-if="requireDialogFormVisible" ref="requireEdit" :categories="formItem.categories" :require-info="requireInfo" />
    </FormDialog>
  </div>
</template>
<script>
import { detail, create } from '@neu/dcam-ui/api/lingyongKJ'
import PageableTable from '@neu/biz-core/components/PageableTable'
import FormDialog from '@neu/biz-core/components/FormDialog'
import RequireEdit from './requireEdit'
import { tree } from '@neu/dcam-ui/api/assetType'

const columns = [
  { title: '资产分类', width: 300, key: 'type',
    render: (h, params) => {
      let txt = params.row.smallTypeName
      if (params.row.middleTypeName) {
        txt = params.row.middleTypeName + ' / ' + txt
      }
      if (params.row.bigTypeName) {
        txt = params.row.bigTypeName + ' / ' + txt
      }
      return h('span', txt)
    }
  },
  { title: '规格型号', width: 100, key: 'specifications' },
  { title: '需求明细', width: 100, key: 'detail' }
]
const formItem = {
  title: '',
  reason: '',
  remark: '',
  categories: '1',
  comprehensive: true,
  recipientRequires: []
}
export default {
  components: {
    PageableTable,
    FormDialog,
    RequireEdit
  },
  props: {
    taskId: {
      required: false,
      type: String,
      default: 'NULL'
    },
    workOrderNum: {
      required: false,
      type: String,
      default: ''
    },
    orderStatus: {
      required: false,
      type: String,
      default: 'NULL'
    }
  },
  data() {
    return {
      typeOptions: [],
      formItem: {
        ...formItem
      },
      requireInfo: {},
      /** 是否显示需求信息 */
      requireDialogFormVisible: false,
      insideColumns: [...columns],
      rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        categories: [{ required: true, message: '类型不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        reason: [{ required: true, message: '申请原因不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    tree('kj').then(response => {
      this.typeOptions = response.data
    })
    this.fetch()
  },
  methods: {
    edit(row) {
      this.requireDialogFormVisible = true
      row.isUpdate = true
      this.requireInfo = row
    },
    remove(row) {
      const i = this.formItem.recipientRequires.lastIndexOf(row)
      this.formItem.recipientRequires.splice(i, 1)
    },
    // 初始化表单数据
    fetch() {
      if (this.workOrderNum !== 'NULL') {
        detail(this.workOrderNum, this.taskId).then(response => {
          this.formItem = {
            ...response.data
          }
        })
      } else {
        this.formItem.recipientRequires = []
      }
    },
    commit() {
      this.$refs.myform.validate((valid) => {
        if (valid) {
          // 需求明细不能为空
          if (this.formItem.recipientRequires.length === 0) {
            return this.$message({
              showClose: true,
              message: '需求明细为空，请填写需求明细后在提交!',
              type: 'error'
            })
          }

          const data = { ...this.formItem }
          if (this.orderStatus === 'revoked') {
            data.workOrderNum = null
            data.taskId = null
          } else {
            data.workOrderNum = this.workOrderNum
            data.taskId = this.taskId
          }
          // data.categories = this.categories
          // ge.x 2022-04-08 增加锁屏功能
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          create(data).then(res => {
            if (res.status === 'success') {
              loading.close()
              this.$emit('cancelNewOrderForm', 'refresh')
            }
          }).catch(() => {
            loading.close()
            this.$emit('cancelNewOrderForm', 'refresh')
          })
        }
      })
    },
    // 取消
    selectCancel() {
      this.requireDialogFormVisible = false
      this.requireInfo = {}
    },
    selectOk() {
      this.$refs.requireEdit.$refs.myform.validate((valid) => {
        if (valid) {
          this.requireDialogFormVisible = false
          if (!this.requireInfo.isUpdate) {
            const result = this.flattenTreeDataClosure(this.typeOptions)
            const trees = this.findParent(this.requireInfo.smallTypeCode, result)

            if (trees[0]) {
              this.requireInfo.bigTypeName = trees[0].name
              this.requireInfo.bigTypeCode = trees[0].code
            }

            if (trees[1]) {
              this.requireInfo.middleTypeName = trees[1].name
              this.requireInfo.middleTypeCode = trees[1].code
            }

            this.formItem.recipientRequires.push(this.requireInfo)
          }
        }
      })
    },
    // 新增
    addRequire() {
      this.requireDialogFormVisible = true
      const v = {}
      v.isUpdate = false
      v.quantity = 1
      this.requireInfo = v
    },
    btnCancel() {
      this.$emit('cancelNewOrderForm', 'refresh')
    },
    // 扁平化树形结构
    flattenTreeDataClosure(data) {
      const treeData = data
      const flattenData = []
      function flattenTree(data, parentKey) {
        data.forEach(ele => {
          const { title, code, children } = ele
          flattenData.push({ title, code, parentKey })
          if (children) {
            flattenTree(children, code)
          }
        })
      }
      flattenTree(treeData, null)
      return flattenData
    },
    findParent(item, flattenTree) {
      const parentArr = [] // 存储所有的父级元素
      function find(item, flattenTree) {
        flattenTree.forEach(ele => {
          if (ele.code === item) {
            parentArr.unshift({ code: ele.code, name: ele.title })
            find(ele.parentKey, flattenTree)
          }
        })
      }
      find(item, flattenTree)
      return parentArr
    },
    // 分类变化
    categorieChange(value) {
      this.formItem.recipientRequires = []
      if (this.formItem.categories === '3' || this.formItem.categories === '4') {
        this.insideColumns = columns.filter(l => l.key !== 'bigTypeName' && l.key !== 'middleTypeName')
      } else {
        this.insideColumns = columns
      }
    }
  }
}
</script>
